#include "IOServicePool.h"
#include <iostream>

IOServicePool::IOServicePool(const unsigned int thread_nums)
    : _io_contexts(thread_nums), _io_works(thread_nums), _next_io_context(0) {
    //将io_context加入work进行监管
    for (int i = 0; i < thread_nums; i++) {
        _io_works[i] = make_unique<io_context::work>(_io_contexts[i]);
    }

    //创建线程，启动io_context
    for (int i = 0; i < thread_nums; i++) {
        _threads.emplace_back([this,i]() {
            _io_contexts[i].run();
        });
    }
}

IOServicePool::~IOServicePool() {
    clog << "IOServicePool::~IOServicePool()" << endl;
}

//循环拿出io_context
io_context &IOServicePool::GetIOContext() {
    auto &ioContext = _io_contexts[_next_io_context++];
    if (_next_io_context == _io_contexts.size())
        _next_io_context = 0;
    return ioContext;
}

//停止时候，work的指针rest，work就会释放，work释放时，io_context就会释放
void IOServicePool::stop() {
    for (auto &work: _io_works) {
        work.reset();
    }
    for (auto &thread: _threads) {
        thread.join();
    }
}
